<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getUserListService,
  addUserService,
  editUserService,
  delectUserService,
  resetUserPasswordService,
  getRoleListService
} from '@/api/user'
import { getDepartments } from '@/api/departments'

const userList = ref([]) // 存储用户列表数据
const departments = ref([]) // 存储部门列表数据
const roles = ref([]) // 存储角色列表数据
const dialogVisible = ref(false) // 控制对话框显示
const dialogTitle = ref('添加用户') // 对话框标题
const loading = ref(false) // 加载状态
const searchForm = ref({
  username: '',
  phone: ''
}) // 搜索表单

const userForm = ref({
  id: '',
  username: '',
  fullName: '',
  phone: '',
  email: '',
  roleId: '',
  departmentId: ''
}) // 用户表单数据

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  fullName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
  departmentId: [{ required: true, message: '请选择部门', trigger: 'change' }]
} // 表单验证规则

const formRef = ref(null) // 表单引用

// 获取用户列表
const getUsers = async () => {
  loading.value = true
  try {
    const res = await getUserListService(searchForm.value)
    if (res.code === 200) {
      userList.value = res.data.records // 确保这里是数组
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
  loading.value = false
}

// 打开添加用户对话框
const handleAdd = () => {
  dialogTitle.value = '添加用户'
  userForm.value = {
    id: '',
    username: '',
    fullName: '',
    phone: '',
    email: '',
    roleId: '',
    departmentId: ''
  }
  dialogVisible.value = true
}

// 打开编辑用户对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  userForm.value = { ...row }
  dialogVisible.value = true
}

// 删除用户
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除该用户?', '提示', {
      type: 'warning'
    })
    const res = await delectUserService(id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      getUsers() // 刷新用户列表
    }
  } catch (error) {
    console.error('删除用户失败:', error)
  }
}

// 重置用户密码
const handleResetPassword = async (id) => {
  try {
    await ElMessageBox.confirm('确认重置该用户密码?', '提示', {
      type: 'warning'
    })
    const res = await resetUserPasswordService(id)
    if (res.code === 200) {
      ElMessage.success('密码重置成功')
    }
  } catch (error) {
    console.error('重置密码失败:', error)
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const service = userForm.value.id ? editUserService : addUserService
        const res = await service(userForm.value)
        if (res.code === 200) {
          ElMessage.success(userForm.value.id ? '编辑成功' : '添加成功')
          dialogVisible.value = false
          getUsers() // 刷新用户列表
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 获取部门列表
const getDepartmentsData = async () => {
  try {
    const res = await getDepartments({
      page: 1,
      pageSize: 100
    })
    if (res.code === 200) {
      departments.value = res.data || []
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  }
}

// 获取角色列表
const getRoles = async () => {
  try {
    const res = await getRoleListService()
    if (res.code === 200) {
      roles.value = res.data || []
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 获取角色显示名称
const getRoleDisplayName = (roleId) => {
  const role = roles.value.find(r => r.roleId === roleId)
  return role ? role.displayName : roleId
}

// 在组件挂载时获取用户列表、部门列表和角色列表
onMounted(() => {
  getUsers()
  getDepartmentsData()
  getRoles()
})
</script>

<template>
  <div class="user-list">
    <div class="search-form">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getUsers">查询</el-button>
          <el-button @click="handleAdd">添加用户</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="userList" v-loading="loading" border stripe>
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="fullName" label="姓名" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="roleId" label="角色">
        <template #default="{ row }">
          <el-tag :type="row.roleId === 'role_sys_admin' ? 'danger' : 'success'">
            {{ getRoleDisplayName(row.roleId) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="departmentName" label="所属部门" />
      <el-table-column label="操作" width="280">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="warning" size="small" @click="handleResetPassword(row.id)">重置密码</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="500px"
        :close-on-click-modal="false"
    >
      <el-form
          ref="formRef"
          :model="userForm"
          :rules="rules"
          label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="姓名" prop="fullName">
          <el-input v-model="userForm.fullName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="userForm.roleId" placeholder="请选择角色" style="width: 100%">
            <el-option
              v-for="role in roles"
              :key="role.roleId"
              :label="role.displayName"
              :value="role.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="departmentId">
          <el-select v-model="userForm.departmentId" placeholder="请选择部门" style="width: 100%">
            <el-option
              v-for="dept in departments"
              :key="dept.departmentId"
              :label="dept.departmentName"
              :value="dept.departmentId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
